<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库单ID" prop="receiptId">
        <el-input v-model="queryParams.receiptId" placeholder="请输入入库单ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料" prop="materialId">
        <el-select v-model="queryParams.materialId" placeholder="请选择物料" clearable>
          <el-option v-for="material in materialList" :key="material.materialId" :label="material.materialName"
            :value="material.materialId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:purchase:receiptItem:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:purchase:receiptItem:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:purchase:receiptItem:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:purchase:receiptItem:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="明细ID" align="center" prop="receiptItemId" />
      <el-table-column label="入库单ID" align="center" prop="receiptId" />
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="批次号" align="center" prop="batchNumber" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:purchase:receiptItem:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:purchase:receiptItem:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改入库单明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="入库单ID" prop="receiptId">
          <el-input v-model="form.receiptId" placeholder="请输入入库单ID" />
        </el-form-item>
        <el-form-item label="物料" prop="materialId">
          <el-select v-model="form.materialId" placeholder="请选择物料" @change="handleMaterialChange">
            <el-option v-for="material in materialList" :key="material.materialId" :label="material.materialName"
              :value="material.materialId" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="0" :precision="2" @change="calculateAmount" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number v-model="form.unitPrice" :min="0" :precision="2" @change="calculateAmount" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="form.amount" placeholder="自动计算" readonly />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReceiptItem, getReceiptItem, delReceiptItem, addReceiptItem, updateReceiptItem } from "@/api/mes/purchase/receiptItem";
import { listMaterial } from "@/api/mes/basic/material";

export default {
  name: "ReceiptItem",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库单明细表格数据
      receiptItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptId: null,
        materialId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        receiptId: [
          { required: true, message: "入库单ID不能为空", trigger: "blur" }
        ],
        materialId: [
          { required: true, message: "物料不能为空", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ]
      },
      // 物料列表
      materialList: []
    };
  },
  created() {
    this.getList();
    this.getMaterialList();
  },
  methods: {
    /** 查询入库单明细列表 */
    getList() {
      this.loading = true;
      listReceiptItem(this.queryParams).then(response => {
        this.receiptItemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取物料列表 */
    getMaterialList() {
      listMaterial().then(response => {
        this.materialList = response.rows;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        receiptItemId: null,
        receiptId: null,
        materialId: null,
        materialName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: 0,
        unitPrice: 0,
        amount: 0,
        batchNumber: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.receiptItemId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库单明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const receiptItemId = row.receiptItemId || this.ids
      getReceiptItem(receiptItemId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库单明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.receiptItemId != null) {
            updateReceiptItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReceiptItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const receiptItemIds = row.receiptItemId || this.ids;
      this.$modal.confirm('是否确认删除入库单明细编号为"' + receiptItemIds + '"的数据项？').then(function () {
        return delReceiptItem(receiptItemIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/purchase/receiptItem/export', {
        ...this.queryParams
      }, `receiptItem_${new Date().getTime()}.xlsx`)
    },
    /** 物料变化处理 */
    handleMaterialChange() {
      const material = this.materialList.find(m => m.materialId === this.form.materialId);
      if (material) {
        this.form.materialName = material.materialName;
        this.form.specification = material.specification;
        this.form.unitOfMeasure = material.unitOfMeasure;
      }
    },
    /** 计算金额 */
    calculateAmount() {
      this.form.amount = (this.form.quantity * this.form.unitPrice).toFixed(2);
    }
  }
};
</script>